package com.itheima.dao;

import com.itheima.utils.DatasourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author huyoufu <https://github.com/huyoufu>
 * @TIME 2020-08-09 09:00
 * @description
 */
@Repository
public class AccountDao {


    public void sub(String from, double money) {
        //自己想办法!!!!
        Connection connection= DatasourceUtil.getConnection();

        String sql="update account set money=money-? where name=?";

        //写jdbc操作数据库

        //获取连接

        PreparedStatement statement=null;
        try {

            //准备statement
            statement=connection.prepareStatement(sql);

            statement.setObject(1,money);
            statement.setObject(2,from);

            //执行sql语句
            statement.execute();

        } catch (SQLException e) {
            //e.printStackTrace();
            //上报给service 层 我不做任何处理
            throw new RuntimeException(e);
        }finally {
            //关闭资源
            if (statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public void add(String to, double money) {
        //自己想办法!!!!
        Connection connection=DatasourceUtil.getConnection();

        String sql="update account set money=money+? where name=?";

        PreparedStatement statement=null;
        try {

            //准备statement
            statement=connection.prepareStatement(sql);

            statement.setObject(1,money);
            statement.setObject(2,to);

            //执行sql语句
            statement.execute();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭资源
            if (statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
